package cn.com.self.apis.file.controller;

import cn.com.self.apis.file.entity.Files;
import cn.com.self.apis.file.vo.FilesVo;
import cn.com.self.apis.file.response.BaseResponse;
import cn.com.self.apis.file.service.intf.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "文件上传下载")
@Controller
public class FileController {

    @Value("${file.attachRootPath}")
    private String attachRootPath;

    @Value("${file.url}")
    public String fileUrl;

    @Autowired
    private IFileService fileService;


    @ResponseBody
    @ApiOperation(value = "测试", position = 1)
    @RequestMapping(value = "/getfile", method = RequestMethod.POST)
    public Map getfile(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        List<Files> files = fileService.findAllFiles();
        System.out.println(files.size());
        result.put("url", "");
        return result;
    }

    /**
     * 上传文件
     *
     * @param request  request
     * @param response response
     * @return Map
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    @ResponseBody
    public BaseResponse<FilesVo> upload(HttpServletRequest request, HttpServletResponse response) {
        return getFilesVoBaseResponse(request);
    }

    /**
     * layui富文本上传文件
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "layui富文本上传图片", position = 1)
    @PostMapping("/layuiUpload")
    public BaseResponse<FilesVo>  layuiUpload(HttpServletRequest request, HttpServletResponse response) {

        return getFilesVoBaseResponse(request);

    }

    /**
     * 富文本编辑器上传图片服务（单张）
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "富文本编辑器上传图片服务（单张", position = 2)
    @ResponseBody
    @RequestMapping(value = "/upload/ueditor/image", method = {RequestMethod.GET, RequestMethod.POST})
    public BaseResponse<FilesVo> uploadUeditorImage(HttpServletRequest request, HttpServletResponse response) {

        return getFilesVoBaseResponse(request);

    }

    /**
     * 富文本编辑器上传图片服务（多张）
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "富文本编辑器上传图片服务（多张")
    @ResponseBody
    @RequestMapping(value = "/upload/ueditor/images", method = {RequestMethod.GET, RequestMethod.POST})
    public BaseResponse<List<FilesVo>> uploadUeditorImages(HttpServletRequest request, HttpServletResponse response) {

        List<FilesVo> filesVoList = new ArrayList<>();
        FilesVo filesVo = new FilesVo();
        List<Files> filesList = fileService.uploads(request);
        for (Files files : filesList) {
            filesVo.setFilename(files.getFilename2());
            filesVo.setOldName(files.getFilename());
            filesVo.setUrl(fileUrl + files.getFilepath());
            filesVo.setRelativeUrl(files.getFilepath());
            filesVo.setFilesize(files.getFilesize());
            filesVo.setId(String.valueOf(files.getId()));
            filesVoList.add(filesVo);
        }
        return new BaseResponse<>(filesVoList);
    }


    /**
     * 下载文件
     *
     * @param date
     * @param file
     * @param request
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "文件下载/展示")
    @ResponseBody
    @RequestMapping(value = "/download/{date}/{file:[a-zA-Z0-9_\\\\.]+}", method = RequestMethod.GET)
    public void download(@PathVariable("date") String date, @PathVariable("file") String file,
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileName");
        String[] strings = file.split("\\.");
        //String fileName = strings[0];//md5转码作为文件名
        System.out.print("文件名==" + fileName);
        if (fileName == null){
            fileName = file;
        }
        String fileType = "txt";
        if (strings.length > 1) {
            fileType = strings[1];
        }
        this.fileService.download(response, attachRootPath + "/" + date + "/" + file, fileType, fileName);
    }


    private BaseResponse<FilesVo> getFilesVoBaseResponse(HttpServletRequest request) {
        FilesVo filesVo = new FilesVo();
        Files files = fileService.upload(request);
        filesVo.setFilename(files.getFilename2());
        filesVo.setOldName(files.getFilename());
        filesVo.setUrl(fileUrl + files.getFilepath());
        filesVo.setRelativeUrl(files.getFilepath());
        filesVo.setFilesize(files.getFilesize());
        filesVo.setId(String.valueOf(files.getId()));
        return new BaseResponse<>(filesVo);
    }

}
